<script setup lang="js">
import { onMounted, reactive, ref } from 'vue'
import { queryCompleteCategoryList } from '@/service/category.js'
import { ElTreeSelect, ElMessage, ElMessageBox } from 'element-plus'
import ImageUpload from '@/components/ImageUpload.vue'
import { listBrand } from '@/service/brand.js'
import ImageUploadList from '@/components/ImageUploadList.vue'
import { useRouter } from 'vue-router'
import { addNewProduct } from '@/service/product.js'
import dayjs from 'dayjs'
const router = useRouter()
const type = ref('add')
const productForm = reactive({
  id: null,
  productName: null,
  tip: null,
  categoryIds: [],
  productImage: '',
  status: 0,
  weight: 1,
  productSpecificationDtoList: [],
  inventoryCountingMethod: 0,
  bannerImages: [],
  detailImages: [],
  manufacturingEnterprise: null,
  brandId: null,
  registrationNumber: null,
  medicalInsuranceNumber: null,
  registrationIdPhoto: [],
  manufacturingDate: null,
  expiryDate: null,
  initialSalesVolume: 0,
  productPackaging: null,
})
const rules = reactive({
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    {
      min: 1,
      max: 30,
      message: '商品名称的长度只能在1到30个字符之间',
      trigger: 'blur',
    },
  ],
  categoryIds: [
    {
      required: true,
      message: '请选择至少一个商品分类',
      trigger: 'change',
    },
  ],
  productImage: [{ required: true, message: '请输入商品图片', trigger: 'change' }],
  inventoryCountingMethod: [
    {
      required: true,
      message: '库存计算方式',
      trigger: 'change',
    },
  ],
  weight: [
    {
      required: true,
      message: '请输入商品权重',
      trigger: 'change',
    },
  ],
  productSpecificationDtoList: [
    {
      required: true,
      message: '请添加商品规格',
      trigger: 'change',
    },
  ],
  bannerImages: [
    {
      required: true,
      message: '请添加商品轮播图',
      trigger: 'change',
    },
  ],
  detailImages: [
    {
      required: true,
      message: '请添加商品详情图',
      trigger: 'change',
    },
  ],
})
const categories = ref([])
const loadingRemoteData = ref(false)
const brandList = ref([])
async function loadRemoteBrandInfo(event) {
  const res = await listBrand(event, 1, 10)
  brandList.value = res.data.records
}
async function loadCategories() {
  const res = await queryCompleteCategoryList()
  categories.value = res.data
  console.log(categories.value)
}
onMounted(() => {
  loadCategories()
})
const productFormRef = ref()
async function valid() {
  try {
    await productFormRef.value.validate()
    // 校验规格列表
    if (!productForm.productSpecificationDtoList || !productForm.productSpecificationDtoList.length) {
      ElMessage.error('请添加商品规格')
      return false
    }
    const length = productForm.productSpecificationDtoList.length
    for (let i = 0; i < length; i++) {
      const productSpecificationName = productForm.productSpecificationDtoList[i].productSpecificationName
      if (!productSpecificationName) {
        ElMessage.error(`请填写第${i + 1}个规格的规格名称`)
        return false
      }
    }
    // 校验生产日期
    if (productForm.manufacturingDate && !productForm.expiryDate) {
      ElMessage.error('请填写到期时间')
      return false
    }
    if (productForm.expiryDate && !productForm.manufacturingDate) {
      ElMessage.error('请填写生产时间')
      return false
    }
    if (productForm.manufacturingDate > new Date()) {
      ElMessage.error('生产日期不可以晚于今天')
      return false
    }
    if (productForm.manufacturingDate > productForm.expiryDate) {
      ElMessage.error('生产日期不可以晚于到期时间')
      return false
    }
    return true
  } catch {
    ElMessage.error('请检查表单是否已经填写完整')
    return false
  }
}

function onTapAddNewSpecification() {
  const specification = {
    productSpecificationName: '',
    productSpecificationImage: '',
    discountPrice: 0,
    originalPrice: 0,
    saleCount: 0,
    sort: 10,
    stock: 0,
  }
  productForm.productSpecificationDtoList.unshift(specification)
}
const uploadUrl = import.meta.env.VITE_FILE_UPLOAD_URL
const headers = ref({
  // 增加 Bearer 前缀（根据后端要求决定是否需要）
  Authorization: `${localStorage.getItem('Authorization') || ''}`,
})
function handleRegistrationIdPhotoUploadSuccess(response) {
  const obj = reactive({})
  obj.name = '注册证件照'
  obj.percentage = '100'
  obj.status = 'success'
  obj.uid = new Date().getTime()
  obj.url = response.data
  productForm.registrationIdPhoto = []
  productForm.registrationIdPhoto.push(obj)
}
function buildForm(form) {
  const params = {}
  params.id = form.id
  params.productName = form.productName
  params.tip = form.tip
  params.categoryIds = form.categoryIds
  params.productImage = form.productImage
  params.status = form.status
  params.weight = form.weight
  params.inventoryCountingMethod = form.inventoryCountingMethod
  params.bannerImages = form.bannerImages
  params.detailImages = form.detailImages
  params.manufacturingEnterprise = form.manufacturingEnterprise
  params.brandId = form.brandId
  params.medicalInsuranceNumber = form.medicalInsuranceNumber
  if (form.registrationIdPhoto.length > 0) {
    params.registrationIdPhoto = form.registrationIdPhoto[0].url
  }
  params.registrationNumber = form.registrationNumber
  if (form.manufacturingDate) {
    params.manufacturingDate = dayjs(form.manufacturingDate).format('YYYY-MM-DD')
  } else {
    params.manufacturingDate = null
  }
  if (form.expiryDate) {
    params.expiryDate = dayjs(form.expiryDate).format('YYYY-MM-DD')
  } else {
    params.expiryDate = null
  }
  params.productSpecificationDtoList = form.productSpecificationDtoList
  params.initialSalesVolume = form.initialSalesVolume
  params.productPackaging = form.productPackaging
  return params
}

async function onTapSaveButton() {
  const flag = await valid()
  if (!flag) {
    return
  }
  const form = JSON.parse(JSON.stringify(productForm))
  console.log(form)
  const params = buildForm(form)
  await addNewProduct(params)
  ElMessage.success('成功添加商品！')
  router.back()
}

function onTapUpdateButton() {
  if (!valid()) return
  router.back()
}

function onTapDeleteButton(index) {
  ElMessageBox.confirm('确定删除该商品规格吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      productForm.productSpecificationDtoList.splice(index, 1)
      ElMessage({
        type: 'success',
        message: '成功删除该商品规格',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
function onTapNavigateToCategoryPage() {
  router.push({ name: 'category' })
}
function onTapNavigateToBrandPage() {
  router.push({ name: 'Brand' })
}
</script>

<template>
  <div class="add-product">
    <h3 v-if="type === 'add'">新增商品</h3>
    <h3 v-if="type === 'edit'">编辑商品</h3>
    <el-form ref="productFormRef" :model="productForm" label-position="right" label-width="120px" :rules="rules">
      <el-divider content-position="left">编辑商品基本信息</el-divider>
      <el-form-item label="商品名称:" prop="productName">
        <el-input
          v-model="productForm.productName"
          placeholder="请输入商品名称"
          maxlength="30"
          show-word-limit
          type="text"
          style="width: 600px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="商品作用提示:" prop="tip">
        <el-input
          v-model="productForm.tip"
          placeholder="请输入商品作用提示(非必填)"
          maxlength="30"
          show-word-limit
          type="text"
          style="width: 600px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="商品分类:" prop="categoryIds">
        <div style="display: flex; align-items: center">
          <el-tree-select
            v-model="productForm.categoryIds"
            :data="categories"
            :props="{
              label: 'name',
              children: 'children',
            }"
            :render-after-expand="false"
            multiple
            placeholder="请选择至少一个商品分类"
            show-checkbox
            style="width: 420px"
            value-key="id"
          />
          <el-link underline="never" type="primary" style="margin-left: 10px" @click="onTapNavigateToCategoryPage">
            新增分类
          </el-link>
        </div>
      </el-form-item>
      <el-form-item label="商品品牌:" style="width: 600px">
        <div style="display: flex; align-items: center">
          <div style="width: 300px">
            <el-select
              v-model="productForm.brandId"
              :loading="loadingRemoteData"
              :remote-method="loadRemoteBrandInfo"
              filterable
              placeholder="请选择商品品牌(非必填)"
              remote
              clearable
            >
              <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item.id"> </el-option>
            </el-select>
          </div>
          <div style="flex: 1">
            <el-link underline="never" type="primary" style="margin-left: 10px" @click="onTapNavigateToBrandPage">
              新增品牌
            </el-link>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="商品图片:" prop="productImage">
        <ImageUpload v-model="productForm.productImage"></ImageUpload>
      </el-form-item>
      <el-form-item label="库存计算方式:" prop="inventoryCountingMethod">
        <el-radio-group v-model="productForm.inventoryCountingMethod">
          <el-radio :value="0">下单减库存</el-radio>
          <el-radio :value="1">付款减库存</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="weight">
        <template #label>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="商品的权重越高，则展示的优先级越高"
            placement="top-start"
          >
            商品权重:
          </el-tooltip>
        </template>
        <el-input-number
          v-model="productForm.weight"
          :min="1"
          :max="100"
          :controls="false"
          :precision="0"
          value-on-clear="max"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="初始销量:">
        <el-tooltip
          class="box-item"
          effect="dark"
          content="商品的初始销量，较高的初始销量可用提升曝光度"
          placement="top-start"
        >
          <el-input-number
            v-model="productForm.initialSalesVolume"
            :min="0"
            :max="99999999"
            :controls="false"
            :precision="0"
            value-on-clear="min"
          ></el-input-number>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="商品状态:" prop="productStatus">
        <el-radio-group v-model="productForm.status">
          <el-radio :value="0">上架</el-radio>
          <el-radio :value="1">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider content-position="left">编辑商品规格</el-divider>
      <el-form-item label="商品规格:" prop="productSpecificationDtoList">
        <el-button type="default" @click="onTapAddNewSpecification"> 新增规格 </el-button>
        <el-table
          :data="productForm.productSpecificationDtoList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          border
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column align="center" label="规格预览图">
            <template #default="scope">
              <el-tooltip class="box-item" effect="dark" content="商品规格图，默认为商品图片" placement="top-start">
                <div style="padding: 4px">
                  <ImageUpload v-model="scope.row.productSpecificationImage"></ImageUpload>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="规格名称">
            <template #default="scope">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="商品规格名称，建议不超过10个字符"
                placement="top-start"
              >
                <el-input
                  v-model="scope.row.productSpecificationName"
                  maxlength="10"
                  placeholder="请输入规格名称"
                  type="text"
                  :input-style="{ 'text-align': 'center' }"
                ></el-input>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="规格价格">
            <template #default="scope">
              <el-tooltip class="box-item" effect="dark" content="商品的实际销售价格" placement="top-start">
                <el-input-number
                  v-model="scope.row.discountPrice"
                  :controls="false"
                  :min="0.01"
                  :precision="2"
                  placeholder="请输入规格价格"
                  style="width: 120px"
                >
                  <template #prefix>
                    <span>￥</span>
                  </template>
                </el-input-number>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="划线价格">
            <template #default="scope">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="商品的划线价格，用于展示(非必填)"
                placement="top-start"
              >
                <el-input-number
                  v-model="scope.row.originalPrice"
                  :controls="false"
                  :min="0.0"
                  :precision="2"
                  placeholder="请输入划线价格"
                  style="width: 120px"
                >
                  <template #prefix>
                    <span>￥</span>
                  </template>
                </el-input-number>
              </el-tooltip>
            </template>
          </el-table-column>
<!--          <el-table-column align="center" label="销量">-->
<!--            <template #default="scope">-->
<!--              <el-tooltip-->
<!--                class="box-item"-->
<!--                effect="dark"-->
<!--                content="商品销量，更高的销量更容易被消费者看到"-->
<!--                placement="top-start"-->
<!--              >-->
<!--                <el-input-number-->
<!--                  v-model="scope.row.saleCount"-->
<!--                  :controls="false"-->
<!--                  :min="0"-->
<!--                  :precision="0"-->
<!--                  placeholder="请输入商品销量"-->
<!--                  style="width: 120px"-->
<!--                >-->
<!--                </el-input-number>-->
<!--              </el-tooltip>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column align="center" label="库存数量">
            <template #default="scope">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="库存数量，库存为0时商品不能够被购买"
                placement="top-start"
              >
                <el-input-number
                  v-model="scope.row.stock"
                  :controls="false"
                  :min="0"
                  :precision="0"
                  placeholder="请输入商品库存"
                  style="width: 120px"
                >
                </el-input-number>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="权重">
            <template #default="scope">
              <el-tooltip
                class="box-item"
                effect="dark"
                content="规格权重，决定规格的展示顺序，最高的权重将作为默认规格"
                placement="top-start"
              >
                <el-input-number
                  v-model="scope.row.sort"
                  :controls="false"
                  :min="0"
                  :max="999999"
                  :precision="0"
                  placeholder="请输入规格权重"
                  style="width: 120px"
                >
                </el-input-number>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="scope">
              <el-button type="danger" @click="onTapDeleteButton(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-divider content-position="left">编辑商品详情</el-divider>
      <el-form-item label="商品轮播图:" prop="bannerImages">
        <ImageUploadList v-model="productForm.bannerImages"></ImageUploadList>
      </el-form-item>
      <el-form-item label="商品详情图:" prop="detailImages">
        <ImageUploadList v-model="productForm.detailImages"></ImageUploadList>
      </el-form-item>
      <el-form-item label="生产企业:">
        <el-input
          v-model="productForm.manufacturingEnterprise"
          placeholder="请输入商品生产企业(非必填)"
          maxlength="30"
          show-word-limit
          type="text"
          style="width: 600px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="产品包装:">
        <el-input
          v-model="productForm.productPackaging"
          placeholder="请输入商品包装(非必填)"
          maxlength="30"
          show-word-limit
          type="text"
          style="width: 600px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="注册证件号:">
        <el-input
          v-model="productForm.registrationNumber"
          placeholder="请输入商品注册证件号(非必填)"
          maxlength="30"
          show-word-limit
          type="text"
          style="width: 600px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="注册证件照:">
        <el-upload
          v-model:file-list="productForm.registrationIdPhoto"
          :headers="headers"
          :on-success="handleRegistrationIdPhotoUploadSuccess"
          :action="uploadUrl"
          accept=".pdf"
        >
          <el-button type="primary">点击上传注册证件照</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="医保编号:">
        <el-input
          v-model="productForm.medicalInsuranceNumber"
          placeholder="请输入商品医保编号(非必填)"
          maxlength="30"
          show-word-limit
          type="text"
          style="width: 600px"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="生产日期:">
        <el-date-picker v-model="productForm.manufacturingDate" placeholder="点击选择" type="date" />
      </el-form-item>
      <el-form-item label="有效期至:">
        <el-date-picker v-model="productForm.expiryDate" placeholder="点击选择" type="date" />
      </el-form-item>
    </el-form>
    <div style="text-align: right">
      <el-button v-if="type === 'add'" type="primary" @click="onTapSaveButton">新增商品</el-button>
      <el-button v-if="type === 'edit'" type="primary" @click="onTapUpdateButton">保存修改</el-button>
    </div>
  </div>
</template>

<style lang="scss">
.add-product {
  padding: 20px;
  background-color: #fff;
}
</style>
